<template>
  <div class="container">
    <a-card class="general-card">
      <template #title>
        <div class="page-header">
          <a-space align="center">
            <a-button shape="circle" @click="goBack">
              <template #icon><icon-arrow-left /></template>
            </a-button>
            <h2 style="margin: 0;">上架操作</h2>
          </a-space>
          <div>
            <a-space>
              <a-tag size="medium" color="blue">{{ inboundDetail?.code || '未知单号' }}</a-tag>
              <a-tag size="medium" :color="getInboundStatusColor(inboundDetail?.status)">
                {{ getInboundStatusText(inboundDetail?.status) || '未知状态' }}
              </a-tag>
            </a-space>
          </div>
        </div>
      </template>
      
      <!-- 基础信息区域 -->
      <a-descriptions
        title="基础信息"
        :column="{ xs: 1, sm: 2, md: 3 }"
        :data="basicInfoData || []"
        :bordered="false"
        :loading="dataLoading && !inboundDetail"
        size="large"
      />
      
      <a-divider />
      
      <!-- 上架操作区域 -->
      <div class="receiving-area">
        <div class="area-title">货物上架信息</div>
        
        <a-table
          :data="detailList"
          :loading="dataLoading"
          :pagination="false"
          :bordered="true"
          row-key="id"
          :rowSelection="rowSelection"
          @selection-change="handleSelectionChange"
        >
          <template #columns>
            <a-table-column title="货物编码" align="center">
              <template #cell="{ record }">{{ record.cargo?.code || '未知' }}</template>
            </a-table-column>
            <a-table-column title="货物名称" align="center">
              <template #cell="{ record }">{{ record.cargo?.name || '未知' }}</template>
            </a-table-column>
            <a-table-column title="规格型号" align="center">
              <template #cell="{ record }">
                <span v-if="record.cargo?.spec && record.cargo?.spec !== '-'">
                  {{ record.cargo?.spec }}
                </span>
                <span v-else style="color: #ccc;">-</span>
              </template>
            </a-table-column>
            <a-table-column title="单位" align="center">
              <template #cell="{ record }">{{ record.cargo?.unit || '个' }}</template>
            </a-table-column>
            <a-table-column title="实收数量" align="center">
              <template #cell="{ record }">{{ record.received_quantity }}</template>
            </a-table-column>
            <a-table-column title="待上架数量" data-index="pendingQuantity" align="center">
              <template #cell="{ record }">
                <span :class="getPendingClass(record)">{{ record.pendingQuantity }}</span>
              </template>
            </a-table-column>
            <a-table-column title="库位" :width="180" align="center">
              <template #cell="{ record }">
                <!-- Make the text clickable -->
                <span 
                  class="location-cell-clickable" 
                  @click="openLocationSelector(record)"
                  :class="{'disabled-click': submitting || record.putaway || !record.pendingQuantity}"
                >
                  {{ record.locationId ? (getLocationNameById(record.locationId) || '未知库位') : '点击选择库位' }}
                </span>
              </template>
            </a-table-column>
            <a-table-column title="上架数量" :width="150" align="center">
              <template #cell="{ record }">
                <a-input-number
                  v-model="record.putawayQuantity"
                  :min="0"
                  :max="record.pendingQuantity"
                  :disabled="record.putaway || !record.pendingQuantity || submitting"
                  @change="(value) => handleQuantityChange(record, value)"
                />
              </template>
            </a-table-column>
            <a-table-column title="状态" align="center">
              <template #cell="{ record }">
                <a-tag :color="getPutawayStatusColor(record)">
                  {{ getPutawayStatusText(record) }}
                </a-tag>
              </template>
            </a-table-column>
            <a-table-column title="操作" fixed="right" align="center">
              <template #cell="{ record }">
                <a-space>
                  <a-button
                    v-if="!record.putaway"
                    type="primary"
                    size="mini"
                    status="success"
                    :disabled="!isPutawayable(record) || submitting"
                    @click="confirmPutaway(record)"
                  >
                    确认上架
                  </a-button>
                  <a-button
                    v-else
                    type="outline"
                    size="mini"
                    disabled
                  >
                    已上架
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
        
        <!-- 表格底部工具栏，按钮统一靠右放置 -->
        <div class="pagination-wrapper">
          <div class="operations-area">
            <a-space>
              <span class="total-count">共 {{ detailList.length }} 条</span>
              <span class="selected-count" v-if="selectedRowKeys.length > 0">
                已选择 {{ selectedRowKeys.length }} 项
              </span>
              <a-button
                type="primary"
                :disabled="!hasSelectedItems || submitting"
                @click="batchPutaway"
              >
                批量上架
              </a-button>
              <a-button
                type="primary"
                status="success"
                :disabled="!canCompletePutaway || submitting"
                @click="completePutaway"
              >
                完成上架
              </a-button>
            </a-space>
          </div>
        </div>
      </div>
    </a-card>
    
    <!-- 库位选择器对话框 -->
    <a-modal
      v-model:visible="locationSelectorVisible"
      title="选择上架库位"
      width="50%"
      :footer="false"
      draggable
      unmountOnClose
    >
      <LocationSelector
        v-if="locationSelectorVisible"
        ref="locationSelectorRef"
        :product-id="currentProduct?.cargo?.id"
        :warehouse-id="inboundDetail?.warehouse_id"
        operation-type="putaway"
        :required-quantity="currentProduct?.pendingQuantity || 0"
        @select="handleLocationSelect"
      />
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, watch, nextTick, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Message, Modal } from '@arco-design/web-vue';
import { useInboundStore } from '@/stores/inbound';
import { useWarehouseStore } from '@/stores/warehouse';
import { IconArrowLeft, IconSearch, IconEdit } from '@arco-design/web-vue/es/icon';
import LocationSelector from '@/components/inventory/LocationSelector.vue';
import dayjs from 'dayjs';
import { formatTime } from '@/utils/datetime';

const route = useRoute();
const router = useRouter();
const inboundStore = useInboundStore();
const warehouseStore = useWarehouseStore();

const inboundId = route.params.id;
const inboundDetail = ref({});
const detailList = ref([]);
const componentLoading = ref(false);
const dataLoading = ref(false);
const locationsLoading = ref(false);
const locationOptions = ref([]);
const warehouseId = ref('');
const submitting = ref(false);

// 表格选择
const selectedRowKeys = ref([]);
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
  modelValue: selectedRowKeys,
  'onUpdate:modelValue': (val) => {
    selectedRowKeys.value = val;
  },
  // 已上架的或不能上架的不能选择
  isDisabled: (record) => {
    return record.putaway || !isPutawayable(record);
  }
});

// 是否有选中项
const hasSelectedItems = computed(() => {
  return selectedRowKeys.value.length > 0;
});

// 是否可以完成上架
const canCompletePutaway = computed(() => {
  // 至少有一项已上架，且所有项都已处理（已上架或待上架数量为0）
  const hasPutaway = detailList.value.some(item => item.putaway);
  const allProcessed = detailList.value.every(item => item.putaway || item.pendingQuantity === 0);
  return hasPutaway && allProcessed;
});

// 从 Store 获取状态映射函数
const { getInboundStatusColor, getInboundStatusText } = inboundStore;

// 货物上架状态色彩
const getPutawayStatusColor = (record) => {
  if (record.putaway) return 'green';
  if (record.pendingQuantity === 0) return 'gray'; // 如果待上架为0，也算完成
  if (record.putawayQuantity > 0 || record.locationId) return 'blue'; // 正在操作中
  return 'gold'; // 待上架
};

// 货物上架状态文本
const getPutawayStatusText = (record) => {
  if (record.putaway) return '已上架';
  if (record.pendingQuantity === 0) return '已完成'; // 待上架为0
  if (record.putawayQuantity > 0) return '部分上架';
  if (record.locationId) return '库位已选';
  return '待上架';
};

// 获取待上架数量样式
const getPendingClass = (record) => {
  if (record.pendingQuantity === 0) return 'pending-zero';
  if (record.putawayQuantity > 0 && record.putawayQuantity < record.pendingQuantity) return 'pending-partial';
  return 'pending-normal';
};

// 设置基础信息 (确保使用导入的 formatTime 和 getInboundStatusText)
const basicInfoData = computed(() => {
  if (!inboundDetail.value) return [];
  
  // 入库类型映射 - 可以在 Store 或 utils 中定义，暂时保留本地
  const inboundTypeMap = {
    'purchase': '采购入库',
    'return': '退货入库',
    'transfer': '调拨入库',
    'other': '其他入库'
  };
  
  // 获取创建人信息
  let creatorDisplay = '未知';
  if (inboundDetail.value.user && inboundDetail.value.user.nickname) {
    creatorDisplay = inboundDetail.value.user.nickname;
  } else if (inboundDetail.value.creator_name) {
    creatorDisplay = inboundDetail.value.creator_name;
  } else if (inboundDetail.value.user && inboundDetail.value.user.username) {
    creatorDisplay = inboundDetail.value.user.username;
  } else if (inboundDetail.value.user_id !== undefined && inboundDetail.value.user_id !== null) {
    creatorDisplay = `ID: ${inboundDetail.value.user_id}`;
  }
  
  // 原始信息数组
  const infoItems = [
    { label: '入库单号', value: inboundDetail.value.code || '-' },
    { label: '状态', value: getInboundStatusText(inboundDetail.value.status) }, // 使用导入的函数
    { label: '仓库', value: inboundDetail.value.warehouse?.name || '-' },
    // 尝试获取入库类型
    { label: '入库类型', value: inboundTypeMap[inboundDetail.value.inbound_type], type: 'inbound_type' }, // 添加 type 标识
    { label: '创建人', value: creatorDisplay },
    { label: '创建时间', value: formatTime(inboundDetail.value.created_at) }, // 使用导入的函数
    { label: '收货完成时间', value: formatTime(inboundDetail.value.receive_time) } // 修改字段名为 receive_time
  ];

  // 过滤掉无效的入库类型
  return infoItems.filter(item => {
    if (item.type === 'inbound_type') {
      // 仅当 value 存在 (即类型被识别) 时保留
      return !!item.value;
    }
    // 其他项总是保留
    return true;
  });
});

// 检查是否可以上架
const isPutawayable = (record) => {
  return !record.putaway && 
    record.pendingQuantity > 0 && 
    record.locationId && 
    record.putawayQuantity !== undefined && 
    record.putawayQuantity > 0;
};

// 处理上架数量变化
const handleQuantityChange = (record, value) => {
  record.putawayQuantity = value;
};

// 返回上一页
const goBack = () => {
  router.push('/inbound/orders');
};

// 获取仓库库位列表
const getLocations = async () => {
  locationsLoading.value = true;
  try {
    if (!inboundDetail.value || !inboundDetail.value.warehouse_id) {
      console.warn('未获取到入库单详情或仓库ID，无法获取库位列表');
      return;
    }
    
    // 获取仓库下所有库位
    const warehouseId = inboundDetail.value.warehouse_id;
    
    // 使用仓库store的缓存机制获取库位列表，不使用forceRefresh
    console.log(`获取仓库 ${warehouseId} 的库位列表...`);
    const locations = await warehouseStore.getLocationsByWarehouse(warehouseId, {
      _t: new Date().getTime() // 添加时间戳，但使用缓存如果有的话
    });
    
    if (!locations) {
      Message.error('获取库位列表失败');
      return;
    }
    
    // 过滤出可用的库位（启用状态）
    const availableLocations = locations.filter(loc => loc.status === 1);
    
    // 更新库位选项
    locationOptions.value = availableLocations;
    
    console.log(`获取到 ${locationOptions.value.length} 个可用库位`, availableLocations.map(l => ({ id: l.id, code: l.code, status: l.status })));
  } catch (error) {
    console.error('获取库位列表失败:', error);
    Message.error(`获取库位列表失败: ${error.message || '未知错误'}`);
  } finally {
    locationsLoading.value = false;
  }
};

// 库位选择相关
const locationSelectorVisible = ref(false);
const locationSelectorRef = ref(null);
const currentProduct = ref(null);

// 打开库位选择器
const openLocationSelector = (record) => {
  if (componentLoading.value || record.putaway || !record.pendingQuantity) {
    return; // 禁用状态下不响应点击
  }
  currentProduct.value = record;
  locationSelectorVisible.value = true;
  
  // 在下一个事件循环中等待组件挂载完成，然后刷新数据
  nextTick(async () => {
    if (locationSelectorRef.value) {
      await locationSelectorRef.value.refreshLocations();
    }
  });
};

// 处理库位选择
const handleLocationSelect = async ({ location, quantity }) => {
  if (!currentProduct.value || !location) {
    Message.error('选择库位失败，请重试');
    return;
  }
  
  console.log('选择库位:', location);
  console.log('默认数量:', quantity);
  
  // 更新UI状态
  currentProduct.value.locationId = location.id;
  if (quantity > 0) {
    currentProduct.value.putawayQuantity = quantity;
  }
  
  // 关闭选择器对话框
  locationSelectorVisible.value = false;
  
  // 获取最新的库位数据
  await getLocations();
};

// 确认上架一个货物
const confirmPutaway = async (record) => {
  if (!isPutawayable(record)) {
    Message.warning('请选择库位并输入上架数量');
    return;
  }
  
  // 安全检查：如果有多个选中项，提示用户可能的混淆
  if (selectedRowKeys.value.length > 1) {
    // 使用确认对话框，明确告知用户将只处理当前记录
    Modal.confirm({
      title: '确认单个上架',
      content: `您已选中多个商品(${selectedRowKeys.value.length}项)，但点击了单个上架按钮。是否只上架当前选择的商品"${record.cargo?.name || '商品'}"？`,
      okText: '继续上架此商品',
      cancelText: '取消',
      onOk: async () => {
        // 清除所有选择状态，确保只处理当前记录
        selectedRowKeys.value = [];
        // 继续执行单个上架逻辑
        await executeSinglePutaway(record);
      }
    });
    return;
  }
  
  // 清除所有选择状态，确保只处理当前记录
  selectedRowKeys.value = [];
  
  // 执行单个上架操作
  await executeSinglePutaway(record);
};

// 执行单个上架的实际逻辑，从confirmPutaway中提取出来
const executeSinglePutaway = async (record) => {
  // 先清除可能存在的加载消息
  clearAllLoadingMessages();
  
  // 生成唯一的消息ID
  const loadingMsgId = showLoadingMessage('正在处理上架请求...', 2000);
  
  try {
    // 先获取最新的库位数据
    await getLocations();
    
    // 确认库位容量是否足够
    const currentLocation = locationOptions.value.find(loc => loc.id === record.locationId);
    if (!currentLocation) {
      Message.error('所选库位不存在，请重新选择');
      clearLoadingMessage(loadingMsgId);
      return;
    }
    
    const capacity = currentLocation.capacity || 0;
    const currentQuantity = currentLocation.current_quantity || 0;
    const availableCapacity = Math.max(0, capacity - currentQuantity);
    
    console.log('上架前检查库位容量:', {
      库位: currentLocation.code,
      当前库存: currentQuantity,
      总容量: capacity,
      可用容量: availableCapacity,
      上架数量: record.putawayQuantity
    });
    
    if (record.putawayQuantity > availableCapacity) {
      Message.error(`库位 ${currentLocation.code} 可用容量不足，最多可上架 ${availableCapacity} 个单位`);
      clearLoadingMessage(loadingMsgId);
      return;
    }
    
    submitting.value = true;
    dataLoading.value = true; // 设置表格加载状态
    
    // 构造上架数据，按后端要求的结构 (order_item_id, location_id, putaway_quantity)
    const putawayItem = {
      order_item_id: record.id,
      location_id: record.locationId,
      putaway_quantity: record.putawayQuantity
    };
    
    // 预先保存货物信息，用于成功消息
    const cargoName = record.cargo?.name || '货物';
    const cargoUnit = record.cargo?.unit || '';
    const putawayQty = record.putawayQuantity;
    const locationName = getLocationNameById(record.locationId);
    
    // 在API调用前就标记为已上架，避免DOM更新问题
    const originalPendingQty = record.pendingQuantity;
    record.pendingQuantity -= record.putawayQuantity;
    record.putawayQuantity = 0;
    
    if (record.pendingQuantity <= 0) {
      record.putaway = true;
    }
    
    // 调用API进行上架
    const result = await inboundStore.putawayInbound(inboundId, { items: [putawayItem] });
    
    // 确保清除加载提示
    clearLoadingMessage(loadingMsgId);
    clearAllLoadingMessages();
    
    if (result) {
      // 先显示成功提示
      Message.success(`已成功将 ${putawayQty} ${cargoUnit} ${cargoName} 上架到 ${locationName}`);
      
      // 使用setTimeout延迟后台数据刷新，避免DOM更新冲突
      setTimeout(async () => {
        try {
          // 强制刷新库位选择器
          await refreshLocationSelector();
          
          // 强制刷新当前页面的库位数据
          await getLocations();
          
          // 重新获取入库单详情
          await getInboundDetail();
        } catch (err) {
          console.error('刷新数据失败:', err);
        } finally {
          submitting.value = false;
          dataLoading.value = false; // 解除表格加载状态
          clearAllLoadingMessages(); // 确保所有加载消息都被清除
        }
      }, 300);
    } else {
      // 恢复原始状态
      record.pendingQuantity = originalPendingQty;
      record.putaway = false;
      
      Message.error('上架失败：服务器未返回预期结果');
      submitting.value = false;
      dataLoading.value = false; // 解除表格加载状态
      clearAllLoadingMessages(); // 确保所有加载消息都被清除
    }
  } catch (error) {
    console.error('上架失败:', error);
    
    // 确保清除加载提示
    clearLoadingMessage(loadingMsgId);
    clearAllLoadingMessages();
    
    // 显示错误消息
    Message.error(`上架失败: ${error.message || '未知错误'}`);
    submitting.value = false;
    dataLoading.value = false; // 解除表格加载状态
  }
};

// 批量确认上架
const batchPutaway = async () => {
  if (selectedRowKeys.value.length === 0) {
    Message.error('请至少选择一个需要上架的物料');
    return;
  }

  // 先清除可能存在的加载消息
  clearAllLoadingMessages();

  // 先获取最新的库位数据
  await getLocations();

  // 过滤掉不满足上架条件的物料并验证库位容量
  const validItems = [];
  const invalidItems = [];

  // 获取待上架的物料
  const selectedItems = detailList.value.filter(item => selectedRowKeys.value.includes(item.id));

  // 批量上架商品详情列表，用于确认提示
  const batchItemsDetails = [];

  for (const item of selectedItems) {
    if (!isPutawayable(item)) {
      invalidItems.push({
        item,
        reason: '未填写库位或数量'
      });
      continue;
    }

    // 验证库位容量
    const location = locationOptions.value.find(loc => loc.id === item.locationId);
    if (!location) {
      invalidItems.push({
        item,
        reason: '所选库位不存在'
      });
      continue;
    }

    const capacity = location.capacity || 0;
    const currentQuantity = location.current_quantity || 0;
    const availableCapacity = Math.max(0, capacity - currentQuantity);

    if (item.putawayQuantity > availableCapacity) {
      invalidItems.push({
        item,
        reason: `库位容量不足 (可用: ${availableCapacity}, 需要: ${item.putawayQuantity})`
      });
      continue;
    }

    // 验证通过，添加到有效项
    validItems.push({
      order_item_id: item.id,
      location_id: item.locationId,
      putaway_quantity: item.putawayQuantity,
      remarks: item.remark
    });
    
    // 添加到详情列表用于显示
    batchItemsDetails.push({
      name: item.cargo?.name || '未知商品',
      code: item.cargo?.code || '-',
      quantity: item.putawayQuantity,
      unit: item.cargo?.unit || '个',
      location: getLocationNameById(item.locationId) || '未知库位'
    });
  }

  // 如果有无效项，显示警告
  if (invalidItems.length > 0) {
    Message.warning(`有 ${invalidItems.length} 项无法上架，请检查`);
    console.warn('无法上架的货物:', invalidItems);
  }

  // 如果没有有效项，返回
  if (validItems.length === 0) {
    Message.error('所选货物均不满足上架条件，请重新选择');
    return;
  }

  // 构建批量上架的详细确认信息
  let confirmContent = `确认对选中的 ${validItems.length} 项货物进行上架操作吗？`;
  
  // 添加详情列表
  if (batchItemsDetails.length > 0) {
    confirmContent += '\n\n上架详情：';
    batchItemsDetails.slice(0, 5).forEach((item, index) => {
      confirmContent += `\n${index+1}. ${item.name} (${item.code}): ${item.quantity} ${item.unit} → ${item.location}`;
    });
    
    // 如果有更多商品，显示省略号
    if (batchItemsDetails.length > 5) {
      confirmContent += `\n... 等共 ${batchItemsDetails.length} 项`;
    }
  }
  
  // 如果有无效项，添加警告
  if (invalidItems.length > 0) {
    confirmContent += `\n\n⚠ 警告：有 ${invalidItems.length} 项无法上架，这些项将被跳过。`;
  }

  try {
    // 使用Modal.confirm代替feedbackRef.showConfirm
    Modal.confirm({
      title: '批量确认上架',
      content: confirmContent,
      okText: '确认上架',
      cancelText: '取消',
      onOk: async () => {
        // 确保先清除之前的所有加载消息
        clearAllLoadingMessages();
        
        // 生成唯一的消息ID
        const batchLoadingMsgId = showLoadingMessage('正在处理批量上架请求...', 2000); // 设置2秒超时自动关闭
        
        try {
          submitting.value = true;
          dataLoading.value = true; // 设置表格加载状态
          
          // 预先更新UI状态，避免DOM更新问题
          // 保存原始状态以便需要恢复
          const originalStates = new Map();
          
          // 对每个选中项进行状态更新
          for (const selectedItem of selectedItems) {
            const validItem = validItems.find(v => v.order_item_id === selectedItem.id);
            if (validItem) {
              // 保存原始状态
              originalStates.set(selectedItem.id, {
                pendingQuantity: selectedItem.pendingQuantity,
                putawayQuantity: selectedItem.putawayQuantity,
                putaway: selectedItem.putaway
              });
              
              // 更新UI状态
              selectedItem.pendingQuantity -= validItem.putaway_quantity;
              selectedItem.putawayQuantity = 0;
              
              if (selectedItem.pendingQuantity <= 0) {
                selectedItem.putaway = true;
              }
            }
          }
          
          // 调用API进行批量上架
          const result = await inboundStore.putawayInbound(inboundId, { items: validItems });
          
          // 确保清除加载提示
          clearLoadingMessage(batchLoadingMsgId);
          
          if (result) {
            // 清空选择
            selectedRowKeys.value = [];
            
            // 显示成功消息
            Message.success(`已成功批量上架 ${validItems.length} 项货物`);
            
            // 使用setTimeout延迟数据刷新，避免DOM更新冲突
            setTimeout(async () => {
              try {
                // 强制刷新库位选择器
                await refreshLocationSelector();
                
                // 强制刷新当前页面的库位数据
                await getLocations();
                
                // 重新获取入库单详情
                await getInboundDetail();
              } catch (err) {
                console.error('刷新数据失败:', err);
              } finally {
                // 确保再次清除所有加载消息
                clearAllLoadingMessages();
                submitting.value = false;
                dataLoading.value = false; // 解除表格加载状态
              }
            }, 300);
          } else {
            // 恢复原始状态
            for (const [id, state] of originalStates.entries()) {
              const item = detailList.value.find(i => i.id === id);
              if (item) {
                item.pendingQuantity = state.pendingQuantity;
                item.putawayQuantity = state.putawayQuantity;
                item.putaway = state.putaway;
              }
            }
            
            // 确保清除加载消息
            clearAllLoadingMessages();
            
            Message.error('批量上架失败：服务器未返回预期结果');
            submitting.value = false;
            dataLoading.value = false; // 解除表格加载状态
          }
        } catch (error) {
          console.error('批量上架失败:', error);
          
          // 确保清除加载提示
          clearLoadingMessage(batchLoadingMsgId);
          clearAllLoadingMessages();
          
          // 显示错误消息
          Message.error(`批量上架失败: ${error.message || '未知错误'}`);
          submitting.value = false;
          dataLoading.value = false; // 解除表格加载状态
        }
      },
      onCancel: () => {
        // 确保取消时也清除所有加载消息
        clearAllLoadingMessages();
      }
    });
  } catch (error) {
    console.error('批量上架操作异常:', error);
    Message.error(`操作异常: ${error.message || '未知错误'}`);
    clearAllLoadingMessages(); // 确保在异常情况下也清除所有加载消息
  }
};

// 完成上架
const completePutaway = async () => {
  if (!canCompletePutaway.value) {
    Message.warning('无法完成上架：请确保至少有一项已上架且所有货物均已处理');
    return;
  }
  
  // 如果有选中项但用户点击了"完成上架"，确保用户理解他们将完成整个上架过程
  if (selectedRowKeys.value.length > 0) {
    Modal.confirm({
      title: '确认完成上架',
      content: `您当前已选中 ${selectedRowKeys.value.length} 项货物，但您点击了完成上架按钮。\n\n确认完成整个入库单的上架流程吗？这将更新该入库单的状态为"已完成"，后续将不能再修改。`,
      okText: '确认完成上架',
      cancelText: '取消',
      onOk: async () => {
        // 清除选择状态
        selectedRowKeys.value = [];
        // 执行完成上架流程
        await executeCompletePutaway();
      }
    });
    return;
  }
  
  // 无选中项时，直接确认
  Modal.confirm({
    title: '完成上架确认',
    content: '确认完成所有货物上架流程吗？这将更新入库单状态为"已完成"。',
    okText: '确认完成',
    cancelText: '取消',
    okButtonProps: { status: 'success' },
    onOk: async () => {
      await executeCompletePutaway();
    }
  });
};

// 执行完成上架操作的实际逻辑
const executeCompletePutaway = async () => {
  try {
    submitting.value = true;
    
    // 调用API更新入库单状态为"已完成"(状态码3)
    const result = await inboundStore.updateInboundStatus(inboundId, 3);
    
    if (result) {
      Message.success('入库单上架完成');
      
      // 延迟跳转，给用户足够时间看到成功消息
      setTimeout(() => {
        router.push('/inbound/orders');
      }, 1500);
    } else {
      Message.error('完成上架失败：服务器未返回预期结果');
      submitting.value = false;
    }
  } catch (error) {
    console.error('完成上架失败:', error);
    Message.error(`完成上架失败: ${error.message || '未知错误'}`);
    submitting.value = false;
  }
};

// 刷新库位选择器
const refreshLocationSelector = async () => {
  console.log('刷新库位选择器数据...');
  try {
    // 如果inboundDetail还未加载，等待
    if (!inboundDetail.value || !inboundDetail.value.warehouse_id) {
      console.log('无入库单详情，无法刷新库位选择器');
      return;
    }
    
    // 获取仓库ID
    const warehouseId = inboundDetail.value.warehouse_id;
    
    // 清除该仓库的库位缓存
    warehouseStore.clearLocationCache(warehouseId);
    console.log(`已清除仓库 ${warehouseId} 的库位缓存`);
    
    // 强制获取最新的库位数据
    console.log(`从服务器强制刷新库位数据，仓库ID: ${warehouseId}`);
    
    // 使用forceRefresh参数强制从服务器重新获取
    const freshLocations = await warehouseStore.getLocationsByWarehouse(warehouseId, {
      forceRefresh: true,
      _t: new Date().getTime() // 添加时间戳避免缓存
    });
    
    console.log(`刷新成功，获取到 ${freshLocations?.length || 0} 个库位`);
    
    // 如果获取成功，重新获取详细的库位数据
    if (freshLocations && freshLocations.length > 0) {
      await getLocations();
      return true;
    }
    
    return false;
  } catch (error) {
    console.error('刷新库位选择器失败:', error);
    return false;
  }
};

// 获取入库单详情
const getInboundDetail = async () => {
  try {
    componentLoading.value = true;
    dataLoading.value = true; // 添加数据加载状态
    const result = await inboundStore.getInboundDetail(inboundId);
  
    if (result) {
      console.log('[PutawayOperation] Fetched Status:', result.status);
    }
    // --- End Debug Log ---

    if (result) {
      inboundDetail.value = result;
      warehouseId.value = result.warehouse_id;
      
      if (result.items && result.items.length > 0) {
        detailList.value = result.items.map(dtoItem => {
          const receivedQty = dtoItem.received_quantity || 0;
          const putawayQty = dtoItem.putaway_quantity || 0;
          const pendingQuantity = Math.max(0, receivedQty - putawayQty);
          const isFullyPutaway = pendingQuantity <= 0;

          // Wrap the returned object with reactive()
          return reactive({
            id: dtoItem.id,
            cargo: dtoItem.cargo,
            quantity: dtoItem.quantity,
            received_quantity: receivedQty,
            pendingQuantity: pendingQuantity,
            putawayQuantity: pendingQuantity > 0 ? pendingQuantity : 0,
            locationId: dtoItem.location_id || null,
            batchNo: dtoItem.batch_no || '',
            productionDate: dtoItem.production_date || null,
            expiryDate: dtoItem.expiry_date || null,
            remark: dtoItem.note || '',
            putaway: isFullyPutaway,
          });
        });
      } else {
         detailList.value = [];
      }
      
      if (warehouseId.value) { 
        await getLocations();
      } else {
        Message.error('获取仓库ID失败，无法加载库位');
        locationOptions.value = []; 
      }
    } else {
       Message.error('获取入库单详情失败');
       detailList.value = [];
    }
  } catch (error) {
    console.error('获取入库单详情失败:', error);
    Message.error('获取入库单详情失败');
    detailList.value = [];
  } finally {
    dataLoading.value = false; // 数据加载完成
    componentLoading.value = false;
  }
};

// 获取库位名称
const getLocationNameById = (locationId) => {
  if (!locationId) return '未选择';
  
  console.log(`尝试获取库位ID为 ${locationId} 的名称，可用库位:`, locationOptions.value.map(l => ({ id: l.id, code: l.code })));
  
  // 先在locationOptions中查找
  const location = locationOptions.value.find(loc => String(loc.id) === String(locationId));
  if (location) {
    console.log(`在locationOptions中找到库位:`, location.code);
    return location.code;
  }
  
  // 如果在locationOptions中找不到，尝试从warehouseStore获取
  if (inboundDetail.value?.warehouse_id) {
    const cachedLocations = warehouseStore.locationCache[`locations_${inboundDetail.value.warehouse_id}`]?.data || [];
    console.log(`locationOptions中未找到, 查询缓存, 缓存库位数量: ${cachedLocations.length}`);
    
    const cachedLocation = cachedLocations.find(loc => String(loc.id) === String(locationId));
    if (cachedLocation) {
      console.log(`在缓存中找到库位:`, cachedLocation.code);
      return cachedLocation.code;
    }
  }
  
  console.log(`未找到ID为 ${locationId} 的库位信息`);
  return `库位#${locationId}`; // 返回库位ID作为后备显示
};

// 组件挂载时初始化数据
onMounted(async () => {
  console.log('上架操作组件初始化，入库单ID:', inboundId);
  componentLoading.value = true;
  
  try {
    // 初始化选择状态
    selectedRowKeys.value = [];
    
    // 获取入库单详情
    await getInboundDetail();
    
    // 获取库位列表
    await getLocations();
    
    // 初始化库位选择器
    await refreshLocationSelector();
    
    // 添加日志记录，便于追踪操作
    console.log('上架操作页面初始化完成', {
      订单详情: inboundDetail.value ? '已加载' : '未加载',
      订单状态: inboundDetail.value ? getInboundStatusText(inboundDetail.value.status) : '未知',
      库位列表: locationOptions.value.length + '个',
      货物数量: detailList.value.length + '项'
    });
  } catch (error) {
    console.error('上架页面初始化失败:', error);
    Message.error('页面加载失败，请刷新重试');
  } finally {
    componentLoading.value = false;
  }
});

// 处理选择变化
const handleSelectionChange = (selectedRows) => {
  // 确保selectedRowKeys与实际选择的行保持同步
  selectedRowKeys.value = selectedRows.map(row => row.id);
  console.log('选中货物变更:', selectedRowKeys.value.length, '项');
};

// 添加全局加载消息ID跟踪
const activeLoadingMessageIds = ref([]);

// 辅助函数：显示加载消息并跟踪ID
const showLoadingMessage = (content, duration = 0) => {
  // 确保先清除之前可能存在的同内容消息
  const existingMsgs = activeLoadingMessageIds.value.filter(id => 
    id.includes(content.replace(/\s+/g, '_').substring(0, 20))
  );
  
  existingMsgs.forEach(id => {
    clearLoadingMessage(id);
  });

  // 生成包含内容信息的唯一ID，便于识别
  const contentKey = content.replace(/\s+/g, '_').substring(0, 20);
  const id = `loading_${contentKey}_${Date.now()}`;
  
  Message.loading({
    content: content,
    duration: duration, // 如果设置了duration>0，消息会自动关闭
    id: id
  });
  
  activeLoadingMessageIds.value.push(id);
  
  // 如果设置了duration>0，在duration后自动从跟踪列表中移除
  if (duration > 0) {
    setTimeout(() => {
      clearLoadingMessage(id);
    }, duration);
  }
  
  return id;
};

// 辅助函数：清除特定加载消息
const clearLoadingMessage = (id) => {
  if (id) {
    Message.clear(id);
    activeLoadingMessageIds.value = activeLoadingMessageIds.value.filter(msgId => msgId !== id);
  }
};

// 辅助函数：清除所有加载消息
const clearAllLoadingMessages = () => {
  activeLoadingMessageIds.value.forEach(id => {
    Message.clear(id);
  });
  activeLoadingMessageIds.value = [];
};

// 组件卸载前清除所有加载消息
onBeforeUnmount(() => {
  clearAllLoadingMessages();
});
</script>

<style scoped>
.container {
  padding: 16px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.general-card {
  margin-bottom: 16px;
  background-color: var(--color-bg-2);
  border-radius: 4px;
}

.receiving-area {
  margin-top: 16px;
}

.area-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-text-1);
  margin-bottom: 12px;
  position: relative;
  padding-left: 12px;
  line-height: 22px;
}

.area-title::before {
  content: '';
  width: 3px;
  height: 16px;
  background-color: var(--color-primary);
  position: absolute;
  left: 0;
  top: 3px;
}

/* 库位选择器点击样式 */
.location-cell-clickable {
  color: var(--color-link);
  cursor: pointer;
}

.location-cell-clickable.disabled-click {
  color: var(--color-text-3);
  cursor: not-allowed;
}

/* 待上架数量样式 */
.pending-zero {
  color: #86909c;
}

.pending-normal {
  color: #165dff;
  font-weight: 500;
}

.pending-partial {
  color: #ff7d00;
  font-weight: 500;
}

/* 标准分页样式 */
.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.operations-area {
  display: flex;
  align-items: center;
}

.total-count,
.selected-count {
  color: var(--color-text-3);
  font-size: 14px;
  margin-right: 16px;
}
</style>